var express = require('express');
var router = express.Router();
var {User} = require("../utils/model");
var {
  startEncrypt,
  checkSession
} = require("../utils")
const { connection } = require('mongoose');
/* GET users listing. */
router.get('/', function(req, res, next) {
  res.send('respond with a resource');
});



router.post("/register",(req,res)=>{
  var body = req.body;
  console.log(body)
  var username = body.username;
  var password = body.password;
  console.log(username,password)
  if(username && password){
    User.findOne({
      username
    }).then(result=>{
      if(result){
        res.send(`<script>alert('用户名已存在'); location.href='/register' </script>`)
      }else{
          User.insertMany({username,password})
          .then(resule=>{
            res.send(`<script>alert('注册成功');location.href='/login?username=${ startEncrypt(username)}' </script>`)
          })
      }
    })
  }
})


router.post("/login",(req,res)=>{
  var body = req.body;
  console.log(body)
  var username = body.username;
  var password = body.password;
  console.log(username,password)
  if(username && password){
    User.findOne({
      username,
      password
    }).then(result=>{
      if(result){
        console.log(username)
        req.session.username = username;
        req.session.logintime = new Date();
        req.session.token = startEncrypt(username);
        res.redirect("/")
      }else{
        res.send("<script>alert('用户名或密码错误');location.href='/login' </script>")
      }
    })
  }
})

router.post("/changepass",(req,res)=>{
  checkSession(req,res,()=>{
    var body = req.body
    console.log(body)
    User.findOne({username:body.username}).then(result=>{
      if(result){
        if(result.password == body.oldpass){
          User.update({username:body.username},
            {$set:{
                password:body.newpass
              }
            }).then(result=>{
              res.json({
                code:200,
                type:1,
                msg:"密码修改成功..."
              })
            }
            )
        }else{
          res.json({
            code:200,
            type:0,
            msg:"旧密码错误..."
          })
        }
      }else{
        res.json({
          code:200,
          type:0,
          msg:"用户名不存在....."
        })
      }
    })
  })
})

module.exports = router;
